'use strict';

const { Service } = require('egg');
const { Op } = require('sequelize');
const ModelName = 'OrderGoods'
const { v4: uuidv4 } = require('uuid');

function createOrderNumber() {
  // 获取当前日期和时间
  let date = new Date();
  let year = date.getFullYear();
  let month = date.getMonth() + 1; // getMonth() 是从0开始的，所以需要+1
  let day = date.getDate();
  let hours = date.getHours();
  let minutes = date.getMinutes();
  let seconds = date.getSeconds();

  // 格式化日期和时间
  month = month < 10 ? '0' + month : month; // 如果月份小于10，前面添加一个0
  day = day < 10 ? '0' + day : day; // 如果日期小于10，前面添加一个0
  hours = hours < 10 ? '0' + hours : hours; // 如果小时小于10，前面添加一个0
  minutes = minutes < 10 ? '0' + minutes : minutes; // 如果分钟小于10，前面添加一个0
  seconds = seconds < 10 ? '0' + seconds : seconds; // 如果秒数小于10，前面添加一个0

  // 创建订单号
  return year + '' + month + '' + day + '' + hours + '' + minutes + '' + seconds;
}
class RouterService extends Service {
  /**
   * 根据分页和搜索条件获取
   * @param {Object} where 查询用户的条件
   * @param {Number} page 当前分页
   * @param {Number} pageSize 当前页每页多少条
   */
  async getPage(where, page, pageSize) {
    return this.ctx.model[ModelName].findAndCountAll({
      where,
      offset: pageSize * (page - 1),
      limit: pageSize,
      order:[
        // id 降序
        ['create_time','ASC']
      ],
      include: [
        { model: this.ctx.model.OrderGoodsDetail, include: [{ model: this.ctx.model.Goods }]},
        { model: this.ctx.model.Member }
      ]
    });
  }

  // 所有列表
  async allList(where) {
    return this.ctx.model[ModelName].findAll({
      where,
      order:[
        // id 降序
        ['create_time','ASC']
      ],
      include: [
          { model: this.ctx.model.OrderGoodsDetail, include: [{ model: this.ctx.model.Goods }]},
          { model: this.ctx.model.Member }
      ]
    });
  }
  async findOne(id) {
    return this.ctx.model[ModelName].findOne({
      where: {
        id,
      },
      include: [
        { model: this.ctx.model.OrderGoodsDetail, include: [{ model: this.ctx.model.Goods }]},
        { model: this.ctx.model.Member },
        { model: this.ctx.model.Address },
      ]
    });
  }
  /**
   * 创建
   * @param {*} data 角色信息
   */
  async create(data) {
    const goodsIds = data.goods.map(el => el.id)
    const findGoodList = await this.app.model.Goods.findAll({
      where: {
        id: {
          [Op.in]: goodsIds
        }
      }
    })
    findGoodList.forEach(good => {
      const filterGood = data.goods.find(good2 => good.id === good2.id)
      if (filterGood.count > good.store_count) {
        throw new Error(`${good.name}库存不足`)
        return
      }
    })
    const order_no = createOrderNumber()
    // 库存充足
    const insertOrder = await this.ctx.model[ModelName].create({
      order_no,
      member_id: data.member_id,
      address_id: data.address_id,
    })
    // 插入明细表
    return this.app.model.OrderGoodsDetail.bulkCreate(data.goods.map(el => {
      return {
        order_id: insertOrder.id,
        goods_id: el.id,
        count: el.count,
      }
    }))
  }

  /**
   * 根据ID修改
   * @param {Number} id ID
   * @param {Object} data 要修改的信息
   */
  async update(id, data) {
    return await this.ctx.model[ModelName].update(data, { where: { id } });
  }

  /**
   * 根据id删除
   * @param {Number}
   */
  async deleteById(id) {
    return await this.ctx.model[ModelName].destroy({ where: { id } });
  }
}

module.exports = RouterService;
